package cn.cloudtogo.server.mysql.controller;

import cn.cloudtogo.common.types.RequestHeaderObject;
import cn.cloudtogo.common.types.Result;
import cn.cloudtogo.support.mysql.table.TableApi;
import cn.cloudtogo.support.mysql.table.TableMetadata;
import cn.cloudtogo.support.mysql.table.TableTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

import static cn.cloudtogo.server.WebResponse.*;

/**
 * @author yaolianhua789@gmail.com
 **/
@RestController
@RequestMapping("/tables")
public class TablesController {

    private final TableApi tableApi;

    public TablesController(TableApi tableApi) {
        this.tableApi = tableApi;
    }

    @PostMapping
    public ResponseEntity<Result<Void>> create(@RequestBody TableTemplate table,
                                               @ApiIgnore RequestHeaderObject requestHeaderObject) {
        tableApi.create(requestHeaderObject, table);
        return created();
    }

    @PutMapping("/{table}")
    public ResponseEntity<Result<Void>> rename(@PathVariable String table,
                                               @RequestParam("newTableName") String name,
                                               @ApiIgnore RequestHeaderObject requestHeaderObject) {
        tableApi.rename(requestHeaderObject, table, name);
        return accepted();
    }

    @DeleteMapping("/{table}")
    public ResponseEntity<Result<Void>> delete(@PathVariable String table,
                                               @ApiIgnore RequestHeaderObject requestHeaderObject) {
        tableApi.delete(requestHeaderObject, table);
        return accepted();
    }

    @GetMapping
    public ResponseEntity<Result<List<String>>> tablesString(@ApiIgnore RequestHeaderObject requestHeaderObject) {
        List<String> tables = tableApi.tables(requestHeaderObject);
        return ok(tables);
    }

    @GetMapping("/{table}/metadata")
    public ResponseEntity<Result<TableMetadata>> tablesMetadata(@PathVariable String table,
                                                                @ApiIgnore RequestHeaderObject requestHeaderObject) {
        TableMetadata tableMetadata = tableApi.tableMetadata(requestHeaderObject, table);
        return ok(tableMetadata);
    }

//    @GetMapping
//    public ResponseEntity<List<TableMetadata>> tablesMetadata( @ApiIgnore RequestHeaderObject requestHeaderObject) {
//        List<TableMetadata> tableMetadataList = tableApi.tablesMetadata(requestHeaderObject, schema);
//        return ok(tableMetadataList);
//    }

}
